// pages/login/login.js
import {
  LOGIN
} from '../../../request/api.js'
import { 
  isValidatePhoneNumber,
  isValidateEmail,
 } from "../../../utils/util";
 import { 
  hex_sha1,
  } from "../../../utils/sha1";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    phoneNumberOrEmail: '',
    password: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  showToast: function(message){
    wx.showToast({
      title: message,
      icon: 'none'
    })
  },

  bindIdInput: function (e) {
    this.data.phoneNumberOrEmail = e.detail.value;
  },
  bindPasswordInput: function (e) {
    this.data.password = e.detail.value;
  },

  fogetPassword: function() {
    wx.navigateTo({
      url: '/pages/account/find_password/find_password',
    })
  },

  login: function () {
    var id = this.data.phoneNumberOrEmail.trim();
    var password = this.data.password.trim();
    if(!id){
      this.showToast('请输入手机号或邮箱');
      return;
    } else if(!isValidatePhoneNumber(id) && !isValidateEmail(id)){
      this.showToast('请输入正确手机号或邮箱');
      return;
    } else if(!password){
      this.showToast('请输入密码');
      return;
    }

    LOGIN({
      'account': id,
      'password': hex_sha1(password),
    }).then(res => {
      this.onResult(res)
    }).catch(err => {
      this.onReject(err)
    })
  },

  register: function(){
    wx.navigateTo({
      url: '/pages/account/register/register',
    })
  },

  onResult: function (res) {
    //接口请求成功
    if (res.data.code == 1) {
      var app = getApp()
      app.globalData.isLogin = true
      app.globalData.userInfo = res.data.result
      app.globalData.userId = res.data.result.id
      wx.showToast({
        title: '登录成功:' + res.data.message,
        icon: 'none'
      });
      var pages = getCurrentPages();
      var prePage = pages[pages.length - 2];
      prePage.setData({
        reload: true,
      });
      wx.navigateBack({
        delta: 1,
      })
    } else {
      this.onFail(res)
    }
  },
  onFail: function (res) {
    //接口请求失败
    wx.showToast({
      title: '登录失败:' + res.data.message,
      icon: 'none'
    })
  },
  onReject: function (err) {
    wx.showToast({
      title: '登录失败:' + err.errMsg,
      icon: 'none'
    })
  }

})